package com.oreilly.ez.account;

import org.assertj.core.util.Arrays;

import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

public class WordStatis {

    public static void main(String[] args) {


        String text = "aabbcc";

        CharacterCountResult ccr = getCharacterCountResult(text);

        System.out.println(ccr);

//        CharacterCountResult characterCountResult = getHighestNum(text);
//        System.out.println(characterCountResult);
    }

    /**
     * get the max count, character
     * @param text
     * @return
     */
    private static CharacterCountResult getCharacterCountResult(String text) {
        Map<Character, Integer> map = new LinkedHashMap<>();
        char[] charArray = text.toCharArray();

        for (char ch : charArray) {
            Character character = Character.valueOf(ch);
            Integer count = map.getOrDefault(character, 0);
            count++;
            map.put(character, count);
        }

//        System.out.println(map);

        CharacterCountResult ccr = new CharacterCountResult();
        int threshHold = 0;
        Set<Character> keySet = map.keySet();
        for (Character ch : keySet) {
            Integer count = map.get(ch);
            int intValue = count.intValue();
            if (intValue > threshHold) {
                ccr.setCh(ch.charValue());
                ccr.setCount(intValue);
                threshHold = intValue;
            }
        }
        return ccr;
    }


    private static CharacterCountResult getHighestNum(String text) {

        char[] charArray = text.toCharArray();

        Optional<CharacterCountResult> first =

                Arrays.asList(charArray).stream().

                        // {a=4, b=3, c=2, d=3, u=1, e=1, x=2, h=1, 8=1, y=1, 9=1}
                        // group by every character, get count
                                collect(Collectors.groupingBy(ch -> ch, Collectors.counting())).

                        // change every map entry to CharacterCountResult { ch: 'a', count: 4 }
                                entrySet().stream().map(entry -> {
                    CharacterCountResult ccr = new CharacterCountResult();
                    ccr.setCh(entry.getKey().toString().charAt(0));
                    ccr.setCount(entry.getValue().intValue());
                    return ccr;
                }).

                        // sort by  number of occurences
                                sorted(Comparator.comparing((CharacterCountResult ccr) -> ccr.getCount()).reversed()).

                        // just get the highest number of occurences
                                findFirst();


        return first.get();
    }
}
